//
//  LXRTopicController.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/17.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRTopicController.h"
#import "LXRTopicCell.h"
#import "LXRTopicModel.h"
#import "LXRCommentViewController.h"
#import "LXRHTTPSessionManager.h"
#import "LXRNewViewController.h"


/**第三方*/
#import "MBProgressHUD+MJ.h"
#import "UIImageView+WebCache.h"
#import "MJExtension.h"
#import "MJRefresh.h"

@interface LXRTopicController ()

/** 任务管理者 */
@property(nonatomic,strong)LXRHTTPSessionManager *manager;
/** 帖子数据 */
@property(nonatomic,strong)NSMutableArray* topics;
/** 当前页码 */
@property(nonatomic)NSInteger page;
/** 当加载下一页数据时需要这个参数 */
@property(nonatomic,copy)NSString* maxtime;
/** 上一次的请求参数 */
@property (nonatomic, strong) NSDictionary *params;
/** 记录上一次选中的索引(或者控制器) */
@property(nonatomic,assign)NSInteger lastSelectIndex;

@end

@implementation LXRTopicController

//标识cell
static NSString* const LXRCellId = @"topic";
/**懒加载*/
-(NSMutableArray *)topics{
    
    if (_topics == nil) {
        _topics = [NSMutableArray new];
    }
    return _topics;
}
-(LXRHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [LXRHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化表格
    [self setupTableView];
    
    //添加刷新控件
    [self setupRefresh];
    
    //加载新的帖子数据
    [self LoadNewTopics];
    
    
    
}
-(void)dealloc{
    LXRLog(@"%@--dealloc",self);
}
/**初始化表格*/
-(void)setupTableView{
    
    // 设置内边距
    CGFloat bottom = self.tabBarController.tabBar.height;
    CGFloat top = LXRTitlesViewH+LXRTitlesViewY;
    self.tableView.contentInset = UIEdgeInsetsMake(top, 0, bottom, 0);
    // 设置滚动条的内边距
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    //隐藏分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //背景清空颜色
    self.tableView.backgroundColor = [UIColor clearColor];
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRTopicCell class])  bundle:nil] forCellReuseIdentifier:LXRCellId];
    //监听通知
    [LXRNoteCenter addObserver:self selector:@selector(tabBarSelect) name:LXRTabBarDidSelectNotification object:nil];
}
/**监听通知方法*/
-(void)tabBarSelect{
    
    //如果是连续选中2次,直接刷新
    if(self.lastSelectIndex == self.tabBarController.selectedIndex
       &&self.view.isShowingOnKeyWindow){
        
        [self.tableView.mj_header beginRefreshing];
    }
    
    //记录这一次选中的索引
    self.lastSelectIndex = self.tabBarController.selectedIndex;
    
}
/**添加刷新控件*/
-(void)setupRefresh{
    //头部刷新控件
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(LoadNewTopics)];
    //根据拖拽比例自动切换透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    [self.tableView.mj_header beginRefreshing];
    //尾部刷新控件
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
    
}

/**根据控制器类型返回请求参数设置*/
-(NSString*)a{
    
    return [self.parentViewController isKindOfClass:[LXRNewViewController class]] ? @"newlist" : @"list";
        

}

#pragma mark - 加载数据
/**加载新的帖子数据*/
-(void)LoadNewTopics{

    //结束上啦
    [self.tableView.mj_footer endRefreshing];
    
    //参数
    NSMutableDictionary* params = [NSMutableDictionary new];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    self.params = params;
    
    
    __weak typeof(self) weakSelf = self;
    
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* responseObject) {
        
        if (weakSelf.params != params) return ;
        
        //存储maxtime
        weakSelf.maxtime =responseObject[@"info"][@"maxtime"];
        
        //字典转模型
        weakSelf.topics = [LXRTopicModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        //刷新数据
        [weakSelf.tableView reloadData];
        
        //结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
        //上拉清空页码
        weakSelf.page = 0;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //if (weakSelf.params != parms) return ;
        //结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
    }];
}
/**加载更多帖子数据*/
-(void)loadMoreTopics{
    
    //结束头部刷新控件
    [self.tableView.mj_header endRefreshing];
    
    self.page++;
    LXRLog(@"%zd",self.page);
    //参数
    NSMutableDictionary* parms = [NSMutableDictionary new];
    parms[@"a"] = self.a;
    parms[@"c"] = @"data";
    parms[@"type"] = @(self.type);
    parms[@"page"] = @(self.page);
    parms[@"maxtime"] = self.maxtime;
    self.params = parms;
    
    LXRWeakSelf;
    //发送请求
    [self.manager GET:@"http://api.budejie.com/api/api_open.php" parameters:parms progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary* responseObject) {
        
        if (weakSelf.params != parms) return ;
        
        //字典转模型
        NSArray* newTopics = [LXRTopicModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        // 存储maxtime
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        [weakSelf.topics addObjectsFromArray:newTopics];
        
        //刷新数据
        [weakSelf.tableView reloadData];
        
        //结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (weakSelf.params != parms) return ;
        //结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        //恢复页码
        weakSelf.page--;
    }];
}


#pragma mark - 数据源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //设置底部刷新控件什么时候显示,当数据为0的时候
    self.tableView.mj_footer.hidden = (self.topics.count == 0);
    
    return self.topics.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LXRTopicCell* cell = [tableView dequeueReusableCellWithIdentifier:LXRCellId];
    
    cell.model = self.topics[indexPath.row];
    
    return cell;
}
#pragma mark - 代理方法
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //取出模型
    LXRTopicModel* model = self.topics[indexPath.row];
    
    //返回这个模型对应的cell高度
    return model.cellHeight;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    LXRCommentViewController* commentVc = [[LXRCommentViewController alloc]init];
    commentVc.model = self.topics[indexPath.row];
    [self.navigationController pushViewController:commentVc animated:YES];
}
@end
